package cn.weakup.thread.exportdemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Dawn
 * @version 1.0.0
 * @desc 模拟数据导出查询
 * @date 2022/5/8
 */
public class ExportDataTest {
    /**
     * 数据导出一次查询的数据块大小
     */
    public static final int PAGE_SIZE = 1000;

    /**
     * 执行线程池
     */
    public static ExecutorService executor = new ThreadPoolExecutor(2, 4, 10,
            TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000), new ThreadPoolExecutor.AbortPolicy());



    public static void main(String[] args) {
        int totalData = queryCountByCondition();

        int threadNum = totalData%PAGE_SIZE==0? totalData/PAGE_SIZE: totalData/PAGE_SIZE+1;

        List<QueryDataTask> tasks = new ArrayList<>();
        QueryDataTask task;
        Map condition = new HashMap();
        for (int i = 0; i < threadNum; i++) {
            task = new QueryDataTask(i, condition);
            tasks.add(task);
        }

        try {
            List<Future<List>> result = executor.invokeAll(tasks);

            System.out.println(result.size());

            // TODO 开辟线程池向excel中写入数据

            executor.shutdown();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
    /**
     * 获取要导出数据总条数
     * @return
     */
    private static int queryCountByCondition(){
        return 102310;
    }

    /**
     * 按照页码查询分页数据
     */
    static class QueryDataTask implements Callable<List> {
        private int pageStart;
        private int pageEnd;
        private Map condition;

        public QueryDataTask(int pageNum, Map condition) {
            this.pageStart = pageNum * PAGE_SIZE + 1;
            this.pageEnd = this.pageStart + PAGE_SIZE;
            this.condition = condition;
        }

        @Override
        public List call() throws Exception {
            System.out.println("执行" + pageStart + "——" + pageEnd + "的数据");
            return queryDataByCondition(pageStart, pageEnd, condition);
        }

        /**
         * 模拟数据查询
         * @param pageStart
         * @param pageEnd
         * @param condition
         * @return
         */
        public List queryDataByCondition(int pageStart, int pageEnd, Map condition){
            int index = pageStart;
            List list = new ArrayList();
            Map data;
            do {
                data = new HashMap(4);
                data.put("key1", index);
                data.put("key2", "value");
                list.add(data);
                index++;
            }while (index < pageEnd);
            return list;
        }
    }

}
